package com.example.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ReqInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        log.info("经过了拦截器");
        //1.从请求头拿到URI /demo/index
        String requestURI = request.getRequestURI();
        log.info(requestURI);

        //2.读取Redis里面内容
        //2.1 先判断Redis里面有没有key
        String redisKey = "req";

        if (!redisTemplate.hasKey(redisKey)) {
            //2.2 没有，创建一个key，并且把值设置为1,设置有效期3分钟
//            redisTemplate.opsForHash().put(redisKey,hashKey,value);
            redisTemplate.opsForHash().put(redisKey, requestURI, 1);
            //单独设置
            redisTemplate.expire(redisKey, 180, TimeUnit.SECONDS);
            log.info("第1次访问");
        } else {
            //2.3 有,原来的访问次数+1 Object ->?-> String -> Integer
            int count = Integer.parseInt(redisTemplate.opsForHash().get(redisKey, requestURI).toString());
            count++;
            log.info("第{}次访问",count);
            redisTemplate.opsForHash().put(redisKey, requestURI, count);

            //2.4 对redis存储的值进行比对，超过阈值10不给放行
            if (count > 10) {
                return false;
            }
        }

        return true;
    }
}
